<template>
  <div :id="`pageContainer${pageIndex}`" ref="pageContainer" class="pageContainer loading"
       :style="pageContainerStyle">
    <v-stage :config="stageConfig"
             @mousemove="handleStageMousemove"
             @mousedown="handleStageMousedown"
             @touchstart="handleStageMousedown"
             @contentContextmenu="handleContentContextmenu"
             ref="stage">
      <v-layer>
        <v-image :config="{image:img,preventDefault: false}"/>
      </v-layer>
      <v-layer ref="layer">
        <!--注释-->
        <component :is="`v-${item.className}`"
                   :config="getAnnotationConfig(item)"
                   v-for="item in annotationList"
                   @click="handleAnnotationClick($event,item)"
                   @touchstart="handleAnnotationClick($event,item)"
                   @mousemove="handleAnnotationMousemove($event,item)"
                   @touchmove="handleAnnotationMousemove($event,item)"
                   :key="item.id"/>
        <!--选区-->
        <component :is="`v-${item.className}`"
                   :config="getAnnotationConfig(item)"
                   v-for="item in selectionList"
                   @mousemove="handleAnnotationMousemove($event,item)"
                   @touchmove="handleAnnotationMousemove($event,item)"
                   :key="item.id"/>
        <!--搜索结果-->
        <component :is="`v-${item.className}`"
                   :config="getAnnotationConfig(item)"
                   v-for="item in searchResultList"
                   @mousemove="handleAnnotationMousemove($event,item)"
                   @touchmove="handleAnnotationMousemove($event,item)"
                   :key="item.id"/>
        <!--<v-transformer ref="transformer"/>-->
      </v-layer>
      <!--<v-layer ref="hoverLayer">-->

      <!--</v-layer>-->
    </v-stage>
    <!--auxiliary画图用的-->
    <!--<canvas width="918" height="1188" class="auxiliary"-->
    <!--        style="width: 612px; height: 792px; z-index: 30; position: absolute;"></canvas>-->
    <!--图片绘制-->
    <!--<canvas width="460" height="595" class="hacc" :class="`canvas${pageIndex}`"-->
    <!--        style="width: 612px; height: 791.421px; background-color: white; z-index: 20; position: absolute;"></canvas>-->
    <!--<div :id="`pageWidgetContainer${pageIndex}`"-->
    <!--     style="position: absolute; top: 0px; left: 0px; width: 612px; height: 792px; z-index: 40; transform: matrix(1, 0, 0, 1, 0, 0); transform-origin: left top; overflow: hidden;"></div>-->
    <!--<div class="pageDebuggerInfo">-->
    <!--  <div>{{pageIndex}}</div>-->
    <!--  <div>{{data.imgSrc}}</div>-->
    <!--</div>-->
  </div>
</template>

<script>
  import vUnderline from "@/components/Marking/src/Shape/vUnderline";
  import vText from "@/components/Marking/src/Shape/vText";
  import VueKonva from "@/components/vue-konva";
  import {addEventListener, removeEventListener} from "@/components/Marking/util/eventManager";

  const {vStage, vLayer, vImage, vLine, vEllipse, vRect, vArrow, vTransformer} = VueKonva

  export default {
    components: {vStage, vLayer, vImage, vText, vLine, vEllipse, vRect, vArrow, vTransformer, vUnderline},
    props: {
      data: Object
    },
    data() {
      return {
        selectShape: null,
        forceText: true,
        img: null
      }
    },
    computed: {
      annotationList() {
        return this.$parent.annotationList.filter(item => item.pageIndex === this.pageIndex)
      },
      selectionList() {
        return this.$parent.selectionList.filter(item => item.pageIndex === this.pageIndex)
      },
      searchResultList() {
        return this.$parent.searchResultList.filter(item => item.pageIndex === this.pageIndex)
      },
      pageIndex() {
        return this.data.pageIndex
      },
      imgSize() {
        return this.data.imgSize
      },
      scale() {
        return this.$parent.scale
      },
      pointerType() {
        return this.$parent.pointerType
      },
      getWord() {
        return this.$parent.getWord
      },
      getPointerPosOnView() {
        return this.$parent.getPointerPosOnView
      },
      getPageIndexByViewPos() {
        return this.$parent.getPageIndexByViewPos
      },
      handleMoveImage() {
        return this.$parent.handleMoveImage
      },
      handleDrawFreeLine() {
        return this.$parent.handleDrawFreeLine
      },
      handleDrawLine() {
        return this.$parent.handleDrawLine
      },
      sendEvent() {
        return this.$parent.sendEvent
      },
      handleDrawEllipse() {
        return this.$parent.handleDrawEllipse
      },
      handleDrawRect() {
        return this.$parent.handleDrawRect
      },
      handleDrawArrow() {
        return this.$parent.handleDrawArrow
      },
      handleDrawFreeText() {
        return this.$parent.handleDrawFreeText
      },
      viewPosToImagePos() {
        return this.$parent.viewPosToImagePos
      },
      removeAnnotation() {
        return this.$parent.removeAnnotation
      },
      handleSelectText() {
        return this.$parent.handleSelectText
      },
      clearSelection() {
        return this.$parent.clearSelection
      },
      searchResultIndex() {
        return this.$parent.searchResultIndex
      },
      isOnText: {
        get() {
          return this.$parent.isOnText
        },
        set(val) {
          this.$parent.isOnText = val
        }
      },
      isOnShape: {
        get() {
          return this.$parent.isOnShape
        },
        set(val) {
          this.$parent.isOnShape = val
        }
      },
      pageContainerStyle() {
        return {
          marginLeft: 'auto',
          marginRight: 'auto',
          width: `${this.imgSize.width * this.scale}px`,
          height: `${this.imgSize.height * this.scale}px`,
          top: `0px`,
        }
      },
      stageConfig() {
        return {
          width: this.imgSize.width * this.scale,
          height: this.imgSize.height * this.scale,
          scale: {
            x: this.scale,
            y: this.scale
          }
        }
      }
    },
    mounted() {
      // this.getLayer().toggleHitCanvas()
      let img = new Image()
      img.onload = e => {
        this.img = img
      }
      img.src = this.data.imgSrc
    },
    methods: {
      handleStageMousemove(e) {
        if (this.pointerType === 'select' && !e.evt.buttons) {
          this.isOnText = !!this.getWord(this.forceText)
          this.isOnShape = false
        }
      },
      handleStageMousedown(e) {
        this.clearSelection()
        if (this.pointerType !== 'hand') {
          e.evt.preventDefault()
        }
        switch (this.pointerType) {
          case "hand":
            if (e.type === 'mousedown') this.handleMoveImage()

            e = e.evt

            const threshold = 100

            e.changedTouches && (e = e.changedTouches[0])
            let startPageY = e.pageY
            let deltaY = 0

            if (this.$parent.scrollHeight <= 0) {
              // 只有一页，没有滚动条
              // 可前页，后页
              // console.log('可前可后')
              const move = e => {
                e.changedTouches && (e = e.changedTouches[0])
                deltaY = e.pageY - startPageY
                if (deltaY < -threshold) {
                  // this.msg = '松开手指，跳转到下一份证据'
                } else if (deltaY > threshold) {
                  // this.msg = '松开手指，跳转到上一份证据'
                } else {
                  // this.msg = ''
                }
              }
              const up = e => {
                // this.msg = ''
                if (deltaY < -threshold) {
                  this.sendEvent('swipe-up')
                }
                if (deltaY > threshold) {
                  this.sendEvent('swipe-down')
                }
                removeEventListener('mousemove', move)
                removeEventListener('mouseup', up)
              }
              addEventListener('mousemove', move)
              addEventListener('mouseup', up)
            } else if (this.$parent.scrollTop === 0) {
              // 只能前页
              // console.log('可前')
              const move = e => {
                e.changedTouches && (e = e.changedTouches[0])
                deltaY = e.pageY - startPageY
                // if (deltaY < -500) {
                //   this.msg = '松开手指，跳转到上一份证据'
                // }
                if (deltaY > threshold) {
                  console.log('aaaaaaaaaaa')
                  // this.msg = '松开手指，跳转到上一份证据'
                } else {
                  // this.msg = ''
                }
              }
              const up = e => {
                // this.msg = ''
                if (deltaY > threshold) {
                  this.sendEvent('swipe-down')
                }
                removeEventListener('mousemove', move)
                removeEventListener('mouseup', up)
              }
              addEventListener('mousemove', move)
              addEventListener('mouseup', up)
            } else if (this.$parent.scrollHeight - 1 <= this.$parent.scrollTop) {
              // 只能后页
              // console.log('可后')
              const move = e => {
                e.changedTouches && (e = e.changedTouches[0])
                deltaY = e.pageY - startPageY
                if (deltaY < -threshold) {
                  // this.msg = '松开手指，跳转到下一份证据'
                } else {
                  // this.msg = ''
                }
                // if (deltaY > 500) {
                //   this.msg = '松开手指，跳转到下一份证据'
                // }
              }
              const up = e => {
                // this.msg = ''
                if (deltaY < -threshold) {
                  this.sendEvent('swipe-up')
                }
                removeEventListener('mousemove', move)
                removeEventListener('mouseup', up)
              }
              addEventListener('mousemove', move)
              addEventListener('mouseup', up)
            }

            break
          case "select":
            this.handleSelect()
            break
          case "freeLine":
            this.handleDrawFreeLine()
            break
          case "line":
            this.handleDrawLine()
            break
          case "ellipse":
            this.handleDrawEllipse()
            break
          case "rect":
            this.handleDrawRect()
            break
          case "arrow":
            this.handleDrawArrow()
            break
          case "freeText":
            this.handleDrawFreeText()
            break
          case "highlight":
            this.handleSelect()
            break
          case "eraser":
            // this.handleEraser()
            break
        }
      },
      handleContentContextmenu(e) {
        e.evt.preventDefault()
      },
      handleAnnotationClick(evt, item) {
        let ev = evt.evt
        if (ev.changedTouches) {
          ev = ev.changedTouches[0]
          ev = {
            clientX: ev.clientX,
            clientY: ev.clientY,
            pageX: ev.pageX,
            pageY: ev.pageY,
            screenX: ev.screenX,
            screenY: ev.screenY,
            type: 'click'
          }
        }
        this.sendEvent("annotation-click", ev, item)
      },
      handleAnnotationMousemove(evt, item) {
        if (this.pointerType === 'select' && !evt.evt.buttons) {
          // console.log('handleAnnotationMousemove', evt)
          if (item.relationId === "selection-rect") return;
          evt.cancelBubble = true
          this.isOnShape = true
          return
        }
        if (this.pointerType === 'eraser' && (evt.evt.buttons === 1 || evt.evt.type === 'touchmove')) {
          this.removeAnnotation(item.relationId)
          this.sendEvent('annotation-change', {
            [item.relationId]: [{
              pageIndex: this.pageIndex,
              data: item.originalData
            }]
          }, 'delete')
        }
      },
      handleSelect() {
        let A = this.getWord(this.forceText)
        this.handleSelectText(A)
      },
      getAnnotationConfig(item) {
        let conf = {
          strokeWidth: item.attrs.strokeWidth || 0,
          stroke: item.attrs.stroke || 'transparent',
          fill: item.attrs.fill || 'transparent',
          hitStrokeWidth: item.attrs.hitStrokeWidth
        }

        if (item.className === 'underline') {
          if (!conf.strokeWidth) conf.strokeWidth = 1
          if (!conf.stroke) conf.stroke = 'black'
          if (!conf.hitStrokeWidth) conf.hitStrokeWidth = conf.strokeWidth + 10
        } else if (item.className === 'rect' || item.className === 'ellipse') {
          if (!conf.strokeWidth && conf.stroke === 'transparent' && conf.fill === 'transparent') {
            conf.fill = 'rgba(179,179,238,0.3)'
          }
        } else if (item.className === 'arrow') {
          if (!conf.strokeWidth) conf.strokeWidth = 1
          if (!conf.stroke) conf.stroke = 'black'
          conf.fill = conf.stroke
          if (!conf.hitStrokeWidth) conf.hitStrokeWidth = conf.strokeWidth + 10
        } else if (item.className === 'line') {
          if (!conf.strokeWidth) conf.strokeWidth = 1
          if (!conf.stroke) conf.stroke = 'black'
          if (!conf.hitStrokeWidth) conf.hitStrokeWidth = conf.strokeWidth + 10
          conf.lineCap = 'round'
          conf.lineJoin = 'round'
          // conf.tension = 0.7
        }

        if (this.searchResultIndex === item.searchResultIndex) {
          conf.fill = 'rgba(251,205,159,0.3)'
        }

        return {
          ...item.attrs,
          id: item.id,
          relationId: `${item.relationId}`,
          ...conf,
          originalData: item
        }
      },
      getStage() {
        return this.$refs.stage.getStage()
      },
      getLayer() {
        return this.$refs.layer.getNode()
      },
      getAllShapes() {
        return this.$refs.layer.getNode().children
      },
      findOne(selector) {
        return this.getStage().findOne(selector)
      },
      selectShapes(imgRect) {
        let x = imgRect.x * this.scale
        let y = imgRect.y * this.scale
        let width = imgRect.width * this.scale
        let height = imgRect.height * this.scale
        let shapes = this.getAllShapes()
        shapes.forEach(item => {
          let res = Konva.Util.haveIntersection({x, y, width, height}, item.getClientRect());
          if (!res) return
          console.log('需要选中', item)
        })
      },
      getIntersection(imgPos) {
        let x = imgPos.x * this.scale
        let y = imgPos.y * this.scale
        return this.$refs.layer.getNode().getIntersection({x, y})
      },
      select(shape) {
        if (shape.hasName('_anchor')) return
        this.selectShape = shape
        let transformerNode = this.$refs.transformer.getNode();
        transformerNode.attachTo(shape)
        transformerNode.getLayer().batchDraw();
      },
    },
    beforeDestroy() {
      this.getStage().destroy()
    }
  };
</script>
<style scoped lang="scss">
  @import "pageContainer";
</style>
